//
//  WBMainViewController.swift
//  DLSwift微博
//
//  Created by 丁浪涛 on 2016/11/7.
//  Copyright © 2016年 丁浪涛. All rights reserved.
//

import UIKit
import SVProgressHUD
class WBMainViewController: UITabBarController {
    
    //定时刷新未读数量
    fileprivate  var  timer: Timer?
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupChildControllers()
        setupComposeBtn()
        //     override var supportedInterfaceOrientations: UIInterfaceOrientationMask = .portrait
 
        setupTimer()
        
        //设置启动新特性视图
        setupNewfeatureView()
        
        
        delegate = self
        //注册通知
        NotificationCenter.default.addObserver(self, selector: #selector(userLogin), name:NSNotification.Name(rawValue: WBUserShouldLoginNotification), object: nil)
     }
    
    deinit {
        //销毁时钟
        timer?.invalidate()
        NotificationCenter.default.removeObserver(self)
    }
    @objc func userLogin(n: Notification)
    {
        print("用户登录通知： \(n)")
        
        var  when = DispatchTime.now()
        if n.object != nil
        {
        SVProgressHUD.setDefaultMaskType(.gradient)
        SVProgressHUD.showInfo(withStatus: "用户登录已经超时 需要重新登录")
        
        //修改延迟时间
            when = DispatchTime.now() +  2
        }
        
        DispatchQueue.main.asyncAfter(deadline: when){
            let nav  = UINavigationController(rootViewController: WBOAuthViewController())
            self.present(nav, animated: true , completion:{() in
                
            })
            
            }
        
     
    }
    
    
    //MARK： - 私有空间
    fileprivate lazy var  composeBtn :UIButton = UIButton.cz_imageButton("tabbar_compose_icon_add", backgroundImageName: "tabbar_compose_button")
    //横竖屏设置  横屏modal
    override var supportedInterfaceOrientations: UIInterfaceOrientationMask{
        return .portrait
        
    }
    @objc fileprivate func composeStatus()
    {
        let vc = UIViewController()
        vc.view.backgroundColor = UIColor.cz_random()
        let nav = UINavigationController(rootViewController: vc);
        present(nav, animated: true, completion: {
            
        })
    }
}
// extension 不能添加属性
extension  WBMainViewController
{
fileprivate func  setupNewfeatureView()
 {
    //0 如果没有登录 不显示新特性
    
    if !WBNetWorkManager.shared.userLogon {
        return
    }
    //1.检查版本是否更新
    
    //2.如果有更新显示新特性 否则显示欢迎页面
  
    let v = isNewVersion ? WBNewFeatureView.newfeatureView() : WBWelcomView.welcomView()
    //3.添加视图
 
    view.addSubview(v)
    }
    
    
    /**
     版本号
     - 在 AppStore 每次升级应用程序，版本号都需要增加，不能递减
     
     - 组成 主版本号.次版本号.修订版本号
     - 主版本号：意味着大的修改，使用者也需要做大的适应
     - 次版本号：意味着小的修改，某些函数和方法的使用或者参数有变化
     - 修订版本号：框架／程序内部 bug 的修订，不会对使用者造成任何的影响
     */
    // 计算型属性 类似OC的只读  不会占用空间 类似方法（函数）
    fileprivate var isNewVersion :Bool
        {
    //1.取当前的版本号
        let currentVersion = (Bundle.main.infoDictionary?["CFBundleShortVersionString"] as! String) 
    //2.取保存在 Document（会被itunes备份）中的版本号。
        let path :String = ("version" as NSString).cz_appendTempDir()
       
        let sandboxVersion =  (try? String(contentsOfFile: path)) ?? ""
        print(path)
        print(sandboxVersion)
    //3.将当前版本号保存在沙盒
    _ =  try? currentVersion.write(toFile: path, atomically: true, encoding: .utf8)
    //4.保存两个版本号 是否一致
        
        return currentVersion != sandboxVersion
    
    }

}


//UITabBarControllerDelegate
extension WBMainViewController: UITabBarControllerDelegate
{
    //将要选择
    // return 是否切换到目标controller
    func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
        print("将要切换到 \(viewController)")
        //获取控制器在数组中的索引
        let  idx = (childViewControllers as NSArray).index(of: viewController)
        //当前为首页 并且再次点击首页tabbar
        if selectedIndex == 0 && idx == selectedIndex {
            //让表格滚动到顶部 
            //获取到控制器
           print("点击首页")
            let nav  = childViewControllers[0] as! UINavigationController
            let vc = nav.childViewControllers[0] as! WBHomeViewController
            vc.tableView?.setContentOffset(CGPoint(x: 0,y: -64), animated: true )
            
            DispatchQueue.main.asyncAfter(deadline: DispatchTime.now()+1, execute: {
                vc.loadData()
            })
             //清除tabbarItem的badgeVaue
            vc.tabBarItem.badgeValue = nil
            UIApplication.shared.applicationIconBadgeNumber = 0
        }
        
        
        
      // 判断目标控制器是否是UIViewcontroller
        return  !viewController.isMember(of: UIViewController.self)
    }
}
//MARK: -放时钟相关的方法
extension WBMainViewController
{
    fileprivate  func  setupTimer(){
     timer  = Timer.scheduledTimer(timeInterval: 60.0, target: self, selector: #selector(updateTimer), userInfo: nil, repeats: true)
 
    }
    @objc fileprivate func updateTimer()
    {
        if !WBNetWorkManager.shared.userLogon {
            return
        }
        
        WBNetWorkManager.shared.unreadCount { (unreadCount) in
            print("\(unreadCount)")
            self.tabBar.items?[0].badgeValue =  (unreadCount > 0) ? "\(unreadCount)" : nil
            
            //设置app Icon的badge 从ios8 以后 要授权后才能显示
            UIApplication.shared.applicationIconBadgeNumber = unreadCount
        }
    }
    
}

//类似oc 中的分类  在swift中用来切分代码块  可以把相近功能的额函数放到一个extension中
//MARK: 设置界面
extension WBMainViewController{
    
    fileprivate func setupComposeBtn()
    {
        
        tabBar.addSubview(composeBtn)
        // 设置按钮的位置
        let  count: CGFloat = CGFloat(childViewControllers.count)
       //将向内缩进宽度减少 ，能够让按钮的宽度变大。盖住容错点，，防止穿帮
        let w  = tabBar.bounds.width / count
        //CGRectInset 正数向内 负数向外
        composeBtn.frame = tabBar.bounds.insetBy(dx: 2*w, dy: 0)
        composeBtn.addTarget(self, action: #selector(composeStatus), for: .touchUpInside)
    }
    
    
    fileprivate  func setupChildControllers(){
        
        //获取沙盒的文件路径(模拟判断是否已经从网络上加载下了数据)
        let docDir = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
        let  jsonPath = (docDir as NSString).appendingPathComponent("demo.json")
        //加载nsdata
        var  data = NSData(contentsOfFile: jsonPath)
        //判断 data 是否有内容 如果没有 说明没有文件
        if data == nil
        {
        //如果没有 从bundle 加载data
         //从bundle 中加载配置json
            let path = Bundle.main.path(forResource: "demo.json", ofType: nil)
            data = NSData(contentsOfFile: path!)
            
            
        }
        //此时 data一定一定内容 就反序列化
        //反序列化 转换成数组
        
        guard    let array = try? JSONSerialization.jsonObject(with: data! as Data , options: []) as? [[String: AnyObject]]
            else
        {
            return
        }
        
        
        
        /*
         //现在很多应用程序中 界面创建都依赖于网络的json
         let arry :[[String: AnyObject]] = [
         ["clsName":"WBHomeViewController" as AnyObject,
         "title":"首页" as AnyObject,
         "imageName":"community" as AnyObject,
         "visitorInfo": ["imageName": "" , "message":"关注一些人，回这里看看有什么惊喜"] as AnyObject
         ],
         ["clsName":"WBMessageViewController" as AnyObject,
         "title":"消息" as AnyObject,
         "imageName":"activespace" as AnyObject
         ,
         "visitorInfo": ["imageName": "visitordiscover_image_message" , "message":"登录后，别人评论你的微博，发给你的消息，都会在这里收到通知"] as AnyObject
         ],
         ["clsName":"UIViewcontroller" as AnyObject],
         ["clsName":"WBDiscoverViewController" as AnyObject,
         "title":"发现" as AnyObject,
         "imageName":"resources" as AnyObject,
         "visitorInfo": ["imageName": "visitordiscover_image_message" , "message":"登录后，你的微博、相册、个人资料会显示在这里，展示给别人"] as AnyObject
         ],
         
         
         ["clsName":"WBProfileViewController" as AnyObject,
         "title":"我的" as AnyObject,
         "imageName":"activepre" as AnyObject,
         "visitorInfo": ["imageName": "visitordiscover_image_profile" , "message":"登录后，最新、最热微博尽在掌握，不再会与实事潮流擦肩而过"] as AnyObject
         ],]
         */
        
        
        
        //    //转换成plist 格式 数据更为直观
        //    (arry as NSArray).write(toFile:"/Users/dinglangtao/Desktop/demo.plist", atomically: true)
        
        
        //数组转->json 序列化
        //    let data = try! JSONSerialization.data(withJSONObject: array, options: [.prettyPrinted])
        ////    let fileURr = NSURL.fileURL(withPath: "/Users/dinglangtao/Desktop/json")
        //    (data as NSData).write(toFile: "/Users/dinglangtao/Desktop/demo.json", atomically: true)
        //
        
        
        //遍历数组 循环创建控制器数组
        var arrM = [UIViewController]()
        for dict in array!
        {
            arrM.append(controller(dict: dict))
            
        }
        //  设置tabbar 控制器
        viewControllers = arrM
        
    }
    //使用字典创建一个子控制器
    private func controller(dict:[String: AnyObject])->UIViewController
    {
        guard let   clsName = dict["clsName"] as? String,
            let title = dict["title"] as? String,
            let imageName = dict["imageName"] as? String,
            let  visitorDict  = dict["visitorInfo"] as? [String:String],
            let cls = NSClassFromString(Bundle.main.namespace + "." + clsName) as? WBBaseViewController.Type
            else
        {
            return UIViewController()
        }
        
        //创建视图控制器
        let  vc =  cls.init()
        vc.title  = title
        //设置控制器的访客信息字典
        vc.visitorInfoDictionary = visitorDict
        
        
        vc.tabBarItem.image = UIImage(named: "icon_" + imageName)
        vc.tabBarItem.selectedImage = UIImage(named:"icon_" +  imageName + "_tab")?.withRenderingMode(.alwaysOriginal)
        //设置tabbar标题字体
        //系统默认是12号字
        vc.tabBarItem.setTitleTextAttributes([NSForegroundColorAttributeName:UIColor.orange], for:.highlighted)
        //      修改字体大小
        //        vc.tabBarItem.setTitleTextAttributes([NSFontAttributeName:UIFont.systemFont(ofSize: 24)], for: UIControlState(rawValue :0))
        let nav = WBNavigationController(rootViewController: vc)
        return  nav
    }
}
